package com.adxon.servlet;

import com.adxon.MsgException;
import com.adxon.cookie.Badge;
import com.adxon.cookie.Station;
import com.adxon.data.Item;
import com.adxon.data.User;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class SettingsServlet extends ServletBase{
	public void doGet(HttpServletRequest req,HttpServletResponse resp)
			throws IOException,ServletException{
		doGet2(req,resp,Station.getCurrentUser(req));
	}
	public void doGet2(HttpServletRequest req,HttpServletResponse resp,Item user)
			throws IOException,ServletException{
		user.getAll(req);
		setAttributes(req,"Settings");
		forward("settings.jsp",req,resp);
	}
	public void doPost(HttpServletRequest req,HttpServletResponse resp)
			throws IOException,ServletException{
		User u=Station.getCurrentUser(req);
		try{
			FileItemIterator t=new ServletFileUpload().getItemIterator(req);
			while(t.hasNext()){
				FileItemStream i=t.next();
				InputStream m=i.openStream();
				//System.out.println(i.getFieldName()+" - "+m+" - ");
				if(i.isFormField()){
					String x=i.getFieldName();
					if(x.equals("d"))    
						u.setDescription(getString(m));
            			//System.out.println(u.getDescription());
                    if(x.equals("x"))
                    	u.setText(getString(m));
            			//System.out.println(u.getText());
                    }
                    u.setTime(0);
				if(i.getFieldName().equals("v")){
					u.setAttachmentType(i.getContentType());
					u.setBits(m);
	    			//System.out.println("stream");
				}
			}
			u.commit();
			Badge b=new Badge();
			b.setOwner(u);
			b.addTo(resp);
		}catch(MsgException e){
			e.getMessage(req);
		}catch(FileUploadException e){
			e.printStackTrace();
		}
		doGet2(req,resp,Station.getCurrentUser(req));
	}
}